//
//  QSGesLockView.m
//  06-手势解锁
//
//  Created by apple on 2017/7/24.
//  Copyright © 2017年 itcast. All rights reserved.
//

#import "QSGesLockView.h"

@interface QSGesLockView()
@property (nonatomic, strong) NSMutableArray *selectedBtns;

@property(nonatomic,assign) CGPoint currentPoint;
@end

@implementation QSGesLockView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 设置默认属性值
        [self setupDefaultData];
        // 设置界面
        [self setupUI];
    }
    
    return self;
}

/**
 *  设置默认属性值
 */
- (void)setupDefaultData
{
    self.lineColor = [UIColor whiteColor];
    self.lineWidth = 5.0;
    self.btnWH = 60.0;
}

/**
 *  设置界面
 */
- (void)setupUI
{
    self.backgroundColor = [UIColor yellowColor];
    
    for (int i = 0; i < 9; i++)
    {
        // 创建按钮
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        
        //添加按钮
        [self addSubview:button];
        //禁止和用户交互
        button.userInteractionEnabled = NO;
        //设置tag
        button.tag = i;
    }
}

#pragma mark - set
- (void)setBtnNormalImage:(NSString *)btnNormalImage
{
    _btnNormalImage = btnNormalImage;
    
    for (int i = 0; i < self.subviews.count; i++) {
        UIButton *btn = [self.subviews objectAtIndex:i];
        
        // 设置按钮背景图
        [btn setBackgroundImage:[UIImage imageNamed:self.btnNormalImage] forState:UIControlStateNormal];
    }
}

- (void)setBtnSelectedImage:(NSString *)btnSelectedImage
{
    _btnSelectedImage = btnSelectedImage;
    
    for (int i = 0; i < self.subviews.count; i++) {
        UIButton *btn = [self.subviews objectAtIndex:i];
        // 设置按钮选中时的图片
        [btn setBackgroundImage:[UIImage imageNamed:self.btnSelectedImage] forState:UIControlStateSelected];
    }
}

- (void)setBtnWH:(CGFloat)btnWH
{
    _btnWH = btnWH;
    
    [self layoutIfNeeded];
}

#pragma mark - touch
/**
 *  手指按下
 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 获取触摸对象
    UITouch * touch = touches.anyObject;
    
    // 获取触摸点
    CGPoint locP = [touch locationInView:touch.view];
    
    // 数组中最后的按钮
    UIButton *lastBtn = self.selectedBtns.lastObject;
    
    // 开始点击
    if (self.selectedBtns.count <= 0) {
        // 判断点是否在按钮内
        for (int i = 0; i < self.subviews.count; i++)
        {
            // 获取按钮
            UIButton * button = self.subviews[i];
            
            if (CGRectContainsPoint(button.frame, locP) && !button.selected)
            {
                button.selected = YES;
                // 把选中按钮添加到数组中
                [self.selectedBtns addObject:button];
                break;
            }
        }
    } else {
        // 判断点是否在按钮内
        for (int i = 0; i < self.subviews.count; i++)
        {
            // 获取按钮
            UIButton * button = self.subviews[i];
            
            if (CGRectContainsPoint(button.frame, locP) && !button.selected)
            {
                button.selected = YES;
                
                // 判断按钮是否在两点的连线上
                CGFloat k = 0.0;
                if (![self number1:button.qs_centerY isEqualToNumber2:lastBtn.qs_centerY withRelError:0.1 andAbsError:0.01]) {
                    k = (button.qs_centerY - lastBtn.qs_centerY) / (button.qs_centerX - lastBtn.qs_centerX);
                }
                
                // 再遍历一次
                [self.subviews enumerateObjectsUsingBlock:^(__kindof UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (obj.selected == NO) {
                        CGFloat k1 = 0.0;
                        if (![self number1:obj.qs_centerY isEqualToNumber2:lastBtn.qs_centerY withRelError:0.1 andAbsError:0.01]) {
                            k1 = (obj.qs_centerY - lastBtn.qs_centerY) / (obj.qs_centerX - lastBtn.qs_centerX);
                        }
                        
                        CGFloat isInclude = [self number1:k isEqualToNumber2:k1 withRelError:0.1 andAbsError:0.01];
                        BOOL betweenX = [self number:obj.qs_centerX betweenNumber:lastBtn.qs_centerX andNumber:button.qs_centerX];
                        BOOL betweenY = [self number:obj.qs_centerY betweenNumber:lastBtn.qs_centerY andNumber:button.qs_centerY];
                        
                        if (isInclude) {
                            if (betweenX || betweenY) {
                                [self.selectedBtns addObject:obj];
                                obj.selected = YES;
                            }
                        }
                    }
                }];
                
                // 把选中按钮添加到数组中
                [self.selectedBtns addObject:button];
                break;
            }
        }
    }
}

/**
 *  手指移动
 */
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 获取触摸对象
    UITouch * touch = touches.anyObject;
    
    // 获取触摸点
    self.currentPoint = [touch locationInView:touch.view];
    
    [self touchesBegan:touches withEvent:event];
    
    // 执行重绘
    [self setNeedsDisplay];
    
}

/**
 *  手指抬起
 */
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //设置self.currentPoint为最后一个按钮的中心点
    UIButton *lastBtn = self.selectedBtns.lastObject;
    self.currentPoint = lastBtn.center;
    
    //获取密码
    NSMutableString * pwdString = [NSMutableString string];
    
    for (UIButton * button in self.selectedBtns)
    {
        [pwdString appendFormat:@"%@",@(button.tag)];
    }
    
    //执行重绘
    [self setNeedsDisplay];
    
    //调用代理
    if ([self.delegate respondsToSelector:@selector(gesLockView:withPwd:)])
    {
        [self.delegate gesLockView:self withPwd:pwdString];
    }
    
    
    // 修改按钮的选中状态为NO
    for (UIButton * button in self.selectedBtns)
    {
        button.selected = NO;
    }
    
    //清除
    [self.selectedBtns removeAllObjects];
    
    //执行重绘
    [self setNeedsDisplay];
}


- (void)drawRect:(CGRect)rect {
    // 判断数组为空 就返回
    if(self.selectedBtns.count == 0) return;
    
    // 创建路径
    UIBezierPath * path = [UIBezierPath bezierPath];
    
    // 设置线宽 颜色
    path.lineWidth = self.lineWidth;
    
    // 设置线头样式 和连接处样式
    path.lineCapStyle = kCGLineCapRound;
    
    path.lineJoinStyle = kCGLineJoinRound;
    
    [self.lineColor set];
    
    // 添加子路径
    for (int i = 0; i < self.selectedBtns.count; i++)
    {
        // 获取按钮
        UIButton * button = self.selectedBtns[i];
        
        // 获取按钮的中心点
        CGPoint point = button.center;
        
        // 判断设置起始点
        if(i == 0)
        {
            [path moveToPoint:point];
        }
        else
        {
            [path addLineToPoint:point];
        }
    }
    
    [path addLineToPoint:self.currentPoint];
    
    // 渲染
    [path stroke];
}

/**
 *  判断两个浮点数是否相等
 */
- (BOOL)number1:(CGFloat)num1 isEqualToNumber2:(CGFloat)num2 withRelError:(CGFloat)relError andAbsError:(CGFloat)absError
{
    if (num1 == num2) return YES;
    
    if (fabs(num1 - num2) < absError ) return YES;
    
    if (fabs(num1) > fabs(num2))
        return (fabs((num1 - num2) / fabs(num1)) < relError ) ? YES : NO;
    
    return (fabs((num1 - num2) / fabs(num2)) < relError ) ? YES : NO;
}

/**
 *  一个浮点数是否在两个数之间
 */
- (BOOL)number:(CGFloat)num1 betweenNumber:(CGFloat)num2 andNumber:(CGFloat)num3
{
    CGFloat minNumber = MIN(num2, num3);
    CGFloat maxNumber = MAX(num2, num3);
    
    if (num1 > minNumber && num1 < maxNumber) {
        return YES;
    }
    return NO;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat btnWidth = kAdaptedWithWidthValue(self.btnWH);
    CGFloat margin = (self.qs_width - btnWidth * 3) / (3 + 1);
    
    for (int i = 0; i < self.subviews.count; i++) {
        UIButton *button = [self.subviews objectAtIndex:i];
        // 布局
        [button mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self).offset(kAdaptedWithHeightValue((i / 3 + 1) * margin) + (i / 3) * btnWidth);
            make.left.mas_equalTo(self).offset(kAdaptedWithWidthValue((i % 3 + 1) * margin) + (i % 3) * btnWidth);
            make.width.height.mas_equalTo(kAdaptedWithWidthValue(btnWidth));
        }];
    }
}

#pragma mark - 懒加载
- (NSMutableArray *)selectedBtns
{
    if (_selectedBtns == nil)
    {
        _selectedBtns = [NSMutableArray array];
    }
    return _selectedBtns;
}
@end
